﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

using Cisoft.IntegrationSystem.BLL;
using Cisoft.IntegrationSystem.Model;

public partial class Business_Cisoft3G_ContactsManage_ContactEdit :WebUI.Page.EditPage
{
    public static Cisoft.Cisoft3G.Model.ContactsMO model;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindContactGroup();
            model = new Cisoft.Cisoft3G.BLL.ContactsBO().GetModel(id);
            FillControls();
        }
    }

    #region 绑定控件
    private void FillControls()
    {
        if (model != null)
        {
            txtAddress.Text = model.CT_Address;
            txtCompany.Text = model.CT_Company;
            txtCompanyAddress.Text = model.CT_CompanyAddress;
            txtDepartment.Text = model.CT_Department;
            txtDuty.Text = model.CT_Duty;
            txtEmail.Text = model.CT_Email;
            txtMobile.Text = model.CT_Mobile;
            ViewState["oldmobile"] = model.CT_Mobile;
            txtName.Text = model.CT_Name;
            ViewState["oldname"] = model.CT_Name;
            txtPhone.Text = model.CT_Phone;
            txtPostCode.Text = model.CT_PostCode;
            txtQQ.Text = model.CT_QQ;
            ddlContactGroup.SelectedValue = model.CG_ContactGroupID_FK.ToString();
        }
    }
    #endregion

    #region 返回事件
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("ContactsManage.aspx");
    }
    #endregion

    #region 填充实体类 ContactsMO FillModel()
    /// <summary>
    /// 填充实体类
    /// </summary>
    /// <returns></returns>
    private Cisoft.Cisoft3G.Model.ContactsMO FillModel()
    {
        if (Page.IsValid)
        {
            model.CT_Address = txtAddress.Text.Trim();
            model.CT_Company = txtCompany.Text.Trim();
            model.CT_CompanyAddress = txtCompanyAddress.Text.Trim();
            model.CT_Department = txtDepartment.Text.Trim();
            model.CT_Duty = txtDuty.Text.Trim();
            model.CT_Email = txtEmail.Text.Trim();
            model.CT_Mobile = txtMobile.Text.Trim();
            model.CT_Name = txtName.Text.Trim();

            model.CT_Phone = txtPhone.Text.Trim();
            model.CT_PostCode = txtPostCode.Text.Trim();
            model.CT_QQ = txtQQ.Text.Trim();
            model.CT_Sex = 1;
            model.CT_Mobile2 = "";
            model.CG_ContactGroupID_FK = int.Parse(ddlContactGroup.SelectedValue);
        }

        return model;
    }
    #endregion

    #region 修改事件
    protected void btnEidt_Click(object sender, EventArgs e)
    {
        string xmlPath = Server.MapPath(Request.ApplicationPath + "/xmlconfig/sys/cis.config");
        string roleid = Cisoft.IntegrationSystem.Common.XMLHelper.GetConfigValue("cisDefaultMemberRole", xmlPath);
        string strError = string.Empty;
        Cisoft.Cisoft3G.BLL.ContactsBO bll = new Cisoft.Cisoft3G.BLL.ContactsBO();
        Cisoft.Cisoft3G.Model.ContactsMO model = FillModel();
        //如果视图中没有该联系人的用户，那么新增
        DataSet ds = bll.GetUserAndContact(" CT_Mobile='" + ViewState["oldmobile"].ToString() + "' and CT_Name='" + ViewState["oldname"].ToString() + "' ");
        if (ds.Tables[0].Rows.Count > 0)
        { 
        }
        else
        {
            UserBO ubll = new UserBO();
            UserMO umodel = new UserMO();
            UserInfoBO uibll = new UserInfoBO();
            UserInfoMO uimodel = new UserInfoMO();

            int uid = ubll.GetMaxID();
            umodel.UserID = uid;
            umodel.UserName = string.Format("CG_{0}",DateTime.Now.ToString("yyyyMMddHHmmss"));
            umodel.UserPassword = new Cisoft.IntegrationSystem.Common.MD5().HashString("123456");
            umodel.UserRealName = ViewState["oldname"].ToString();
            umodel.Userrole = int.Parse(roleid);
            umodel.UserApplyDate = DateTime.Now;
            umodel.UserGroupID = 0;

            uimodel.UI_UserID_FK = uid;
            uimodel.UI_Phone = ViewState["oldmobile"].ToString();
            uimodel.UI_JoblName = "";

            try
            {
                ubll.AddRecord(umodel);

                uibll.Add(uimodel);
            }
            catch (Exception ex)
            {
            }
        }

        //如果有，则修改
        try
        {
            if (bll.MobileIsExsist(ViewState["oldmobile"].ToString(), txtMobile.Text.Trim()) > 0)
            {
                PageError(ModalPopupExtender2, lblTS, btnBack_ts, "该手机号码已经在通讯录中存在！",Request.RawUrl);
                return;
            }
            else
            {
                //修改用户
                UpdateUser(ViewState["oldname"].ToString(), ViewState["oldmobile"].ToString(), model.CT_Name, model.CT_Mobile);
                bll.Update(model);
            }
        }
        catch (Exception ex)
        {

            strError = ex.Message;
        }
        if (!string.IsNullOrEmpty(strError))
        {
            //PageError("修改联系人信息失败！失败原因如下：" + strError + "。", Request.RawUrl);
            PageError(ModalPopupExtender2, lblTS, btnBack_ts, "修改联系人信息失败！失败原因如下：" + strError, Request.RawUrl);
        }
        else
        {
            //PageRight("修改联系人信息成功！", "ContactsManage.aspx", "点击返回", "");
            PageRight(ModalPopupExtender2, lblTS, btnBack_ts, "<h4>修改联系人信息成功！</h4>", "ContactsManage.aspx");
            //PageRight(ModalPopupExtender2, lblTS, btnBack_ts, "<h4>修改联系人信息成功！</h4>", Request.RawUrl);
        }

    }
    #endregion

    #region 绑定联系人组
    private void BindContactGroup()
    {
        ShowColumns(ddlContactGroup, 0, 0, "CG_ContactGroupID", "CG_ParentID", "CG_GroupName", "CG_ContactGroup");
    }
    #endregion

    #region 下拉框显示树型

    /// <summary>
    /// 组合框显示所有级别（无限级级别）
    /// </summary>
    /// <param name="dropList">组合框名称</param>
    /// <param name="iDepth">深度</param>
    ///  <param name="iParentID">父类ID</param>int iParentID
    public void ShowColumns(DropDownList dropList, int iDepth, int iParentID, string id, string pid, string name, string tableName)
    {
        //定义变量
        int iCount = 0;
        int iSum = 0;
        string strGroupName = "";
        string strGroupID = "";
        DataSet ds = new DataSet();

        ds = new Cisoft.Cisoft3G.BLL.ContactGroupBO().GetList(" " + pid + "=" + iParentID + "  order by cg_order desc");

        iCount = ds.Tables[0].Rows.Count;

        if (iCount != 0)
        {
            //iSum深度处理
            iSum = iDepth + 1;

            for (int i = 0; i < iCount; i++)
            {
                if (i == (iCount - 1))
                {
                    strGroupName = replaceWord(GetDepth("┗" + ds.Tables[0].Rows[i][name].ToString(), iSum));
                    strGroupID = ds.Tables[0].Rows[i][id].ToString();

                    dropList.Items.Add(new ListItem(strGroupName, strGroupID));
                }
                else
                {
                    strGroupName = replaceWord(GetDepth("┗" + ds.Tables[0].Rows[i][name].ToString(), iSum));
                    strGroupID = ds.Tables[0].Rows[i][id].ToString();

                    dropList.Items.Add(new ListItem(strGroupName, ds.Tables[0].Rows[i][id].ToString()));
                }
                ShowColumns(dropList, iSum, Int32.Parse(ds.Tables[0].Rows[i][id].ToString()), id, pid, name, tableName);
            }
        }
    }

    /// <summary>
    /// 字符串插入"│"字符
    /// </summary>
    /// <param name="str">需要插入"│"的字符串</param>
    /// <param name="i">插入"│"字符串的索引位置</param>
    /// <returns></returns>
    private static string GetDepth(string strGroupName, int iCount)
    {
        for (int i = 1; i < iCount; i++)
        {
            strGroupName = strGroupName.Insert(0, "│");
        }

        return strGroupName;
    }

    /// <summary>
    /// 将指定字符串里的“&nbsp;”替换为空字符
    /// </summary>
    /// <param name="strText"></param>
    /// <returns></returns>
    private string replaceWord(string strText)
    {
        string outText = strText.Replace("&nbsp;", " ");
        return outText;
    }

    #endregion

    #region 修改用户
    private void UpdateUser(string oldname,string oldmobile,string realname,string mobile)
    {
        UserBO ubll = new UserBO();
        UserMO umodel = new UserMO();

        UserInfoBO uibo = new UserInfoBO();
        UserInfoMO uimo = new UserInfoMO();

        Cisoft.Cisoft3G.BLL.ContactsBO bll = new Cisoft.Cisoft3G.BLL.ContactsBO();

        DataSet ds = bll.GetUserAndContact(" CT_Name='" + oldname + "' and  CT_Mobile='" + oldmobile + "' ");
        if (ds.Tables[0].Rows.Count > 0)
        {
            int uid = int.Parse(ds.Tables[0].Rows[0]["US_UserID"].ToString());
            umodel = ubll.GetUserInfo(uid);
            if (umodel != null)
            {
                umodel.UserRealName = realname;
                ubll.EditRecord(umodel);
            }

            uimo = uibo.GetModel(uid);
            if (uimo != null)
            {
                uimo.UI_Phone = mobile;
                uibo.Update(uimo);
            }
        }
    }
    #endregion
}
